import { useState, useEffect, useCallback, useRef } from 'react';
    import io from 'socket.io-client';

    // Socket.IO服务器URL配置
    const SOCKET_URL = process.env.NODE_ENV === 'production' 
      ? 'https://api.example.com' 
      : 'http://localhost:3001';

    /**
     * 自定义Hook，用于处理Socket.IO连接
     * @param {string} namespace - 可选的命名空间
     * @param {Object} options - 配置选项
     * @returns {Object} 包含Socket.IO方法和状态的对象
     */
    const useSocketIO = (namespace = '', options = {}) => {
      const [isConnected, setIsConnected] = useState(false);
      const [error, setError] = useState(null);
      const [lastMessage, setLastMessage] = useState(null);
      
      const socketRef = useRef(null);
      const eventHandlersRef = useRef({});
      
      const {
        autoConnect = true,
        reconnection = true,
        reconnectionAttempts = 5,
        reconnectionDelay = 1000,
        reconnectionDelayMax = 5000,
        timeout = 20000,
        auth = {},
        query = {},
        onConnect = () => {},
        onDisconnect = () => {},
        onError = () => {},
      } = options;

      /**
       * 连接到Socket.IO服务器
       */
      const connect = useCallback(() => {
        // 如果已经连接，先关闭
        if (socketRef.current && socketRef.current.connected) {
          socketRef.current.disconnect();
        }

        try {
          // 构建Socket.IO URL和选项
          const url = namespace ? `${SOCKET_URL}/${namespace}` : SOCKET_URL;
          
          // 添加token（如果有）到auth对象
          const token = localStorage.getItem('authToken');
          const authWithToken = token ? { ...auth, token } : auth;
          
          // 创建Socket.IO连接
          socketRef.current = io(url, {
            reconnection,
            reconnectionAttempts,
            reconnectionDelay,
            reconnectionDelayMax,
            timeout,
            auth: authWithToken,
            query,
          });
          
          // 设置事件处理器
          socketRef.current.on('connect', () => {
            setIsConnected(true);
            setError(null);
            console.log('Socket.IO连接已建立');
            onConnect();
          });
          
          socketRef.current.on('disconnect', (reason) => {
            setIsConnected(false);
            console.log(`Socket.IO连接已断开: ${reason}`);
            onDisconnect(reason);
          });
          
          socketRef.current.on('connect_error', (err) => {
            setError(`Socket.IO连接错误: ${err.message}`);
            console.error('Socket.IO连接错误:', err);
            onError(err);
          });
          
          // 注册已保存的事件处理器
          Object.entries(eventHandlersRef.current).forEach(([event, handlers]) => {
            handlers.forEach(handler => {
              socketRef.current.on(event, handler);
            });
          });
        } catch (err) {
          setError(err.message || 'Socket.IO连接失败');
          console.error('Socket.IO连接失败:', err);
        }
      }, [
        namespace, reconnection, reconnectionAttempts, 
        reconnectionDelay, reconnectionDelayMax, timeout, 
        auth, query, onConnect, onDisconnect, onError
      ]);

      /**
       * 发送事件到Socket.IO服务器
       * @param {string} event - 事件名称
       * @param {any} data - 事件数据
       * @param {Function} callback - 可选的回调函数
       * @returns {boolean} 是否发送成功
       */
      const emit = useCallback((event, data, callback) => {
        if (socketRef.current && socketRef.current.connected) {
          if (callback) {
            socketRef.current.emit(event, data, callback);
          } else {
            socketRef.current.emit(event, data);
          }
          return true;
        } else {
          console.error('Socket.IO未连接，无法发送事件');
          return false;
        }
      }, []);

      /**
       * 添加事件监听器
       * @param {string} event - 事件名称
       * @param {Function} handler - 处理函数
       * @returns {Function} 用于移除处理函数的函数
       */
      const on = useCallback((event, handler) => {
        // 保存处理函数到引用
        if (!eventHandlersRef.current[event]) {
          eventHandlersRef.current[event] = [];
        }
        eventHandlersRef.current[event].push(handler);
        
        // 如果socket已连接，立即添加监听器
        if (socketRef.current) {
          socketRef.current.on(event, handler);
        }
        
        // 返回一个函数，用于移除此处理函数
        return () => off(event, handler);
      }, []);

      /**
       * 移除事件监听器
       * @param {string} event - 事件名称
       * @param {Function} handler - 处理函数
       */
      const off = useCallback((event, handler) => {
        // 从引用中移除处理函数
        if (eventHandlersRef.current[event]) {
          eventHandlersRef.current[event] = eventHandlersRef.current[event].filter(h => h !== handler);
          if (eventHandlersRef.current[event].length === 0) {
            delete eventHandlersRef.current[event];
          }
        }
        
        // 如果socket已连接，移除监听器
        if (socketRef.current) {
          socketRef.current.off(event, handler);
        }
      }, []);

      /**
       * 一次性事件监听器
       * @param {string} event - 事件名称
       * @param {Function} handler - 处理函数
       */
      const once = useCallback((event, handler) => {
        if (socketRef.current) {
          socketRef.current.once(event, handler);
        }
      }, []);

      /**
       * 断开Socket.IO连接
       */
      const disconnect = useCallback(() => {
        if (socketRef.current) {
          socketRef.current.disconnect();
          socketRef.current = null;
        }
        setIsConnected(false);
      }, []);

      /**
       * 监听任何事件
       * @param {Function} handler - 处理函数
       * @returns {Function} 用于移除处理函数的函数
       */
      const onAny = useCallback((handler) => {
        if (socketRef.current) {
          socketRef.current.onAny(handler);
        }
        
        // 保存处理函数到引用
        if (!eventHandlersRef.current['*any*']) {
          eventHandlersRef.current['*any*'] = [];
        }
        eventHandlersRef.current['*any*'].push(handler);
        
        // 返回一个函数，用于移除此处理函数
        return () => {
          if (socketRef.current) {
            socketRef.current.offAny(handler);
          }
          
          if (eventHandlersRef.current['*any*']) {
            eventHandlersRef.current['*any*'] = eventHandlersRef.current['*any*'].filter(h => h !== handler);
            if (eventHandlersRef.current['*any*'].length === 0) {
              delete eventHandlersRef.current['*any*'];
            }
          }
        };
      }, []);

      // 初始连接
      useEffect(() => {
        if (autoConnect) {
          connect();
        }
        
        // 清理函数
        return () => {
          disconnect();
        };
      }, [autoConnect, connect, disconnect]);

      // 添加通用消息监听器，用于更新lastMessage
      useEffect(() => {
        const messageHandler = (data) => {
          setLastMessage(data);
        };
        
        const unsubscribe = onAny(messageHandler);
        
        return () => {
          unsubscribe();
        };
      }, [onAny]);

      return {
        socket: socketRef.current,
        isConnected,
        error,
        lastMessage,
        connect,
        disconnect,
        emit,
        on,
        off,
        once,
        onAny,
      };
    };

    export default useSocketIO;
